<?php

namespace App\Livewire\Components;

use Illuminate\Database\Eloquent\Builder;
use Livewire\Component;
use App\Models\Article as ArticleModel;
use Livewire\WithPagination;

class Article extends Component
{
    use WithPagination;

    public $category_id;

    public $year;

    public $keyword;

    public function mount($category_id = false, $year = false, $keyword = '')
    {
        $this->category_id = $category_id;
        $this->year = $year;
        $this->keyword = $keyword;
    }

    public function render()
    {
        $category_id = $this->category_id;
        $year = $this->year;
        $keyword = $this->keyword;
        $articles = ArticleModel::query()
            ->select(['id', 'category_id', 'title', 'description', 'reading_quantity', 'comment_quantity', 'created_at'])
            ->with('category')
            ->when($category_id, function (Builder $query, string $category_id) {
                $query->where('category_id', $category_id);
            })
            ->when($year, function (Builder $query, int $year) {
                $query->whereYear('created_at', $year);
            })
            ->when($keyword, function (Builder $query, string $keyword) {
                $query->where('title', 'like', "%{$keyword}%");
            })
            ->where('status', 1)
            ->orderByDesc('id')
            ->paginate(10);
        return view('livewire.components.article', [
            'articles' => $articles,
        ]);
    }
}

